package com.scs.application.modules.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.device.dto.TaskBuildDto;
import com.scs.application.modules.device.entity.DevicePlanTask;
import com.scs.application.modules.device.enums.DeviceBusMap;
import com.scs.application.modules.device.mapper.DevicePlanItemMapper;
import com.scs.application.modules.device.mapper.DevicePlanTaskMapper;
import com.scs.application.modules.device.service.DevicePlanTaskService;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  设备计划任务 服务实现类
 */
@Service
public class DevicePlanTaskServiceImpl extends BaseServiceImpl<DevicePlanTaskMapper, DevicePlanTask> implements DevicePlanTaskService {
    @Resource
    private DevicePlanItemMapper devicePlanItemMapper;

    @Override
    public boolean saveOrUpdate(DevicePlanTask entity) {
        if (entity.isNewRecord()) {
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(DeviceBusMap.getSerialKey(entity.getBusType())));
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public RestResult buildByPlan(String taskbusType) {
        RestResult restResult = RestResult.ok();

        String planType = "";
        if (StringUtils.isNotBlank(taskbusType)) {
            planType = taskbusType.replace("_task_", "_plan_");
        }
        List<TaskBuildDto> taskBuildDtoList = devicePlanItemMapper.getListForTaskBuild(planType);
        if (ObjectUtil.length(taskBuildDtoList) == 0) {
            restResult.setMsg("没有可生成的任务");
            return restResult;
        }

        Map<String,List<String>> busKeyMap = new HashMap<String,List<String>>();
        Map<String,Integer> busKeyIndexMap = new HashMap<String,Integer>();
        if (StringUtils.isNotBlank(taskbusType)) {
            busKeyMap.put(taskbusType,serialRuleAdapter.getSerialRuleService().batchGenerateCode(DeviceBusMap.getSerialKey(taskbusType),taskBuildDtoList.size()));
            busKeyIndexMap.put(taskbusType,0);
        } else {
            int count = Long.valueOf(taskBuildDtoList.stream().filter(item -> item.getBusType().equals(DeviceBusMap.plan_maintain)).count()).intValue();
            if (count > 0) {
                busKeyMap.put(DeviceBusMap.device_task_maintain,serialRuleAdapter.getSerialRuleService().batchGenerateCode(DeviceBusMap.device_task_maintain,count));
                busKeyIndexMap.put(DeviceBusMap.device_task_maintain,0);
            }

            count = Long.valueOf(taskBuildDtoList.stream().filter(item -> item.getBusType().equals(DeviceBusMap.plan_inspection)).count()).intValue();
            if (count > 0) {
                busKeyMap.put(DeviceBusMap.device_task_inspection,serialRuleAdapter.getSerialRuleService().batchGenerateCode(DeviceBusMap.device_task_inspection,count));
                busKeyIndexMap.put(DeviceBusMap.device_task_inspection,0);
            }

            count = Long.valueOf(taskBuildDtoList.stream().filter(item -> item.getBusType().equals(DeviceBusMap.plan_metering)).count()).intValue();
            if (count > 0) {
                busKeyMap.put(DeviceBusMap.device_task_metering,serialRuleAdapter.getSerialRuleService().batchGenerateCode(DeviceBusMap.device_task_metering,count));
                busKeyIndexMap.put(DeviceBusMap.device_task_metering,0);
            }
        }

        List<DevicePlanTask> planTaskList = new ArrayList<>();
        DevicePlanTask task;
        for(TaskBuildDto taskBuild : taskBuildDtoList) {
            task = new DevicePlanTask();
            BeanUtil.copyProperties(taskBuild,task);
            task.setBusType(task.getBusType().replace("_plan_", "_task_"));
            task.setBusKey(busKeyMap.get(task.getBusType()).get(busKeyIndexMap.get(task.getBusType())));
            task.setFlowStatus(GlobalConsts.FLOW_START_VALUE);
            task.setTaskName(StrUtil.format("{}-第{}次执行", taskBuild.getPlanName(),"1"));
            busKeyIndexMap.put(task.getBusType(), busKeyIndexMap.get(task.getBusType()) + 1);
            planTaskList.add(task);
        }
        this.saveBatch(planTaskList);
        restResult.setMsg(StrUtil.format("生成任务{}个",planTaskList.size()));
        return restResult;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void afterHandleFlowChange(FlowContext flowContext, DevicePlanTask newEntity) {
        if (!flowContext.isEndNode()) {
            return;
        }
    }


    @Override
    public void beforeHandleFlowChange(FlowContext flowContext, DevicePlanTask newEntity) {
        // 开始执行
        if (flowContext.getButton().getCode().equals("execBegin")) {
                newEntity.setStartTime(DateUtils.nowDate(DateUtils.YYYYMMDDHHMMSS_PATTER2));
            newEntity.setBusUser(UserUtils.currentUser().getName());
        }
    }
}
